import { getTop } from 'api/resource'
import Storage from '@/utils/storage'

// 听阅 作文 修辞 累积 归类复习 教子有方 课件 作文课件 教案 论文
const catStorage = new Storage('category')

const category = {
  state: {
    top: catStorage.get()
  },

  mutations: {
    SET_TOP: (state, top) => {
      state.top = top
    }
  },

  actions: {
    // 获取一级目录
    GetTops({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.top) {
          resolve(state.top)
        } else {
          getTop().then(res => {
            commit('SET_TOP', res)
            catStorage.set(res)
            resolve(res);
          }).catch(error => {
            reject(error);
          });
        }
      });
    },

    // 根据name获取id
    GetTopId({ commit, state }, name) {
      return new Promise((resolve, reject) => {
        if (state.top) {
          const id = state.top.filter(v => v.name === name)[0].id
          resolve(id)
        } else {
          getTop().then(res => {
            commit('SET_TOP', res)
            catStorage.set(res)
            const id = state.top.filter(v => v.name === name)[0].id
            resolve(id);
          }).catch(error => {
            reject(error);
          });
        }
      });
    }
  }
}

export default category;
